<?php

namespace app\api\controller\wanlshop;

use app\api\model\wanlshop\Invoice;
use app\admin\model\wanlshop\AgentOrder;
use app\admin\model\wanlshop\UserShare;
use app\admin\model\wanlshop\ShareOrder;
use addons\wanlshop\library\WanlSdk\Common;
use app\api\model\wanlshop\GoodsSku;
use app\api\model\wanlshop\OrderGoods;
use app\common\controller\Api;
use app\common\model\UserFinanceLog;
use think\Cache;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\Log;
use think\Request;
use app\api\model\wanlshop\Order as orderModel;
use app\api\model\wanlshop\OrderGift;
use app\api\model\wanlshop\WithdrawalCash as WithdrawalCashModel;
use app\api\service\wanlshop\WithdrawalCash;
use app\api\model\wanlshop\Goods;
use app\api\controller\Thirdplatform;
use app\api\model\wanlshop\OfflineLog;
use app\api\service\wanlshop\ActCashBack;
use app\admin\model\wanlshop\Share;

/**
 * WanlShop订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    // 订单模块Model
    protected $orderModel = null;
    // 回购订单模块
    protected $orderGiftModel = null;
    // 用户模块
    protected $userModel = null;

    // 提现服务
    protected $withdrawalCashService = null;
    // 提现model
    protected $withdrawalCashModel = null;
    // 商品model
    protected $goodsModel = null;
    // 唯品尚
    protected $thrService = null;
    // 活动返现服务
    protected $actCashBackService = null;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->orderModel = new orderModel();
        $this->orderGiftModel = new OrderGift();
        $this->userModel = new \app\admin\model\User();
        $this->withdrawalCashService = new WithdrawalCash();
        $this->withdrawalCashModel = new WithdrawalCashModel();
        $this->goodsModel = new Goods();
        $this->thrService = new Thirdplatform();
        $this->actCashBackService = new ActCashBack();
    }

    /**
     * 获取订单列表
     *
     * @ApiSummary  (WanlShop 订单接口获取订单列表)
     * @ApiMethod   (GET)
     * 2020年5月12日23:25:40
     *
     * @param string $state 状态
     */
    public function getOrderList()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $state = $this->request->request('state');
        if ($state && $state != 0) {
            $where['state'] = $state;
        }
        $where['status'] = 'normal';
        $where['user_id'] = $this->auth->id;
        // 列表
        $list = model('app\api\model\wanlshop\Order')
            ->with([
                'orderItem' => function ($query) {
                    $query->field('id,order_id,title,goods_id,image,difference,price,market_price,number,refund_status,original_order_id,type')->where('type', 'new');
                },
                'pay',
                'shop' => function ($query) {
                    $query->field('id,shopname');
                },
            ])
            ->where($where)
            ->order('createtime desc')
            ->paginate()
            ->toArray();

        foreach ($list['data'] as $key => $val) {
            foreach ($val['order_item'] as $k => $item) {
                $buyback_time = $item['original_order_id'] ? date('Y-m-d H:i:s', orderModel::where('id', $item['original_order_id'])->value('createtime')) : 0;
                $list['data'][$key]['order_item'][$k]['original_buytime'] = $buyback_time;
            }
            $list['data'][$key]['order_type_text'] = orderModel::getOrderType($val['id']);
            if ($val['state'] == 5) {
                $list['data'][$key]['state_text'] = (new \app\admin\model\wanlshop\Refund())->getRefundStateText($val['id'], $val['user_id']);
            }
        }

        $this->success('ok', $list);
    }

    /**
     * 获取购买过的商品
     *
     * @ApiSummary  (WanlShop 订单接口获取订单列表)
     * @ApiMethod   (GET)
     * 2020年5月12日23:25:40
     *
     * @param string $state 状态
     */
    public function getBuyList()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $order_ids = [];
        foreach (model('app\api\model\wanlshop\Order')->where(['user_id' => ['eq', $this->auth->id], 'state' => ['in', '2,3,4,6'], 'status' => ['eq', 'normal']])->select() as $order) {
            $order_ids[] = $order['id'];
        }
        $goods = model('app\api\model\wanlshop\OrderGoods')
            ->where('order_id', 'in', $order_ids)
            ->select();
        // 列表
        $list = model('app\api\model\wanlshop\Goods')
            ->where('id', 'in', array_keys(array_flip(array_column($goods, 'goods_id'))))
            ->field('id, image, title, price')
            ->order('updatetime desc')
            ->paginate();
        $this->success('ok', $list);
    }


    /**
     * 查询用户店铺订单记录
     *
     * @ApiSummary  (查询用户店铺订单记录 1.0.2升级)
     * @ApiMethod   (POST)
     *
     * @param string $shop_id 店铺ID
     */
    public function getOrderListToShop()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $shop_id = $this->request->post('shop_id');
            $shop_id ? '' : ($this->error(__('Invalid parameters')));
            $list = model('app\api\model\wanlshop\Order')
                ->where(['shop_id' => $shop_id, 'user_id' => $this->auth->id, 'status' => 'normal'])
                ->field('id,shop_id,order_no,state')
                ->order('updatetime desc')
                ->select();
            // 订单状态:1=待支付,2=待发货,3=待收货,4=待评论,5=售后订单(已弃用),6=已完成,7=已取消
            foreach ($list as $row) {
                $row['goods'] = model('app\api\model\wanlshop\OrderGoods')
                    ->where(['order_id' => $row->id])
                    ->field('id,title,image,difference,price,market_price,number,refund_status')
                    ->select();
            }
            $this->success(__('发送成功'), $list);
        }
        $this->error(__('非法请求'));
    }

    /**
     * 获取订单详情
     *
     * @ApiSummary  (WanlShop 订单接口获取订单详情)
     * @ApiMethod   (GET)
     *
     * @param string $id 订单ID
     */
    public function getOrderInfo()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $id = $this->request->request('id');
        $id ? $id : ($this->error(__('非法请求')));
        $order = model('app\api\model\wanlshop\Order')
            ->with([
                'orderItem' => function ($query) {
                    $query->with(['goodsItem' => function ($query) {
                        $query->withField('id,platform');
                    }])->withField('id,goods_id,title,image,difference,price,market_price,actual_payment,discount_price,freight_price,number,refund_id,refund_status,original_order_id,type');
                }, 'pay'
            ])
            ->where(['id' => $id, 'user_id' => $this->auth->id])
            ->find();

        $order->goods = $order->order_item;
        unset($order->order_item);

        $order ? $order : ($this->error(__('网络异常')));
        // 输出配置
        $config = get_addon_config('wanlshop');
        $order['config'] = $config['order'];
        switch ($order['state']) {
            case 1:
                $express = [
                    'context' => '付款后，即可将宝贝发出',
                    'status' => '尚未付款',
                    'time' => date('Y-m-d H:i:s', $order['createtime'])
                ];
                break;
            case 2:
                $express = [
                    'context' => '商家正在处理订单',
                    'status' => '已付款',
                    'time' => date('Y-m-d H:i:s', $order['paymenttime'])
                ];
                break;
            default: // 获取物流
                $eData = model('app\api\model\wanlshop\KuaidiSub')
                    ->where(['express_no' => $order['express_no']])
                    ->find();
//				echo "<pre>";
//				var_dump($eData['data']);exit;
                // 兼容PHP7.4	1.1.5升级
                if (!empty($eData['data'])) {
                    $ybData = json_decode($eData['data'], true);
                    $express = $ybData[0];
                } else {
                    $express = [
                        'status' => '已发货',
                        'context' => '包裹正在等待快递小哥揽收~',
                        'time' => date('Y-m-d H:i:s', $order['delivertime'])
                    ];
                }
        }
        // 获取物流
        $order['logistics'] = $express;
        // 获取地址
        $order['address'] = model('app\api\model\wanlshop\OrderAddress')
            ->where(['order_id' => $id, 'user_id' => $this->auth->id])
            ->order('isaddress desc')
            ->field('id,name,mobile,address,address_name')
            ->find();
        $order['s_name'] = '';
        if ($order['real_store_id']) {
            $order['s_name'] = \app\api\model\wanlshop\Shop::where('id', $order['real_store_id'])->value('shopname');
        }
        if ($order['invoice_id']) {
            $order['s_name'] = \app\api\model\wanlshop\Shop::where('id', Invoice::where('id', $order['invoice_id'])->value('shopid'))->value('shopname');
        }
        // 获取店铺
        $order['shop'] = $order->shop ? $order->shop->visible(['shopname']) : [];
        foreach ($order['goods'] as $item) {
            $buyback_time = $item['original_order_id'] ? date('Y-m-d H:i:s', orderModel::where('id', $item['original_order_id'])->value('createtime')) : 0;
            $item['original_buytime'] = $buyback_time;
        }
        $this->success('ok', $order);
    }

    /**
     * 确认收货
     *
     * @ApiSummary  (WanlShop 订单接口确认收货)
     * @ApiMethod   (POST)
     *
     * @param string $id 订单ID
     */
    public function confirmOrder()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $id ? $id : ($this->error(__('非法请求')));
            // 判断权限
            $order = model('app\api\model\wanlshop\Order')
                ->where(['id' => $id, 'state' => 3, 'user_id' => $this->auth->id])
                ->find();
            if (!$order) {
                $this->error(__('订单异常'));
            }

            Db::startTrans();
            try {
                // 获取支付 1.1.2升级
                $pay = model('app\api\model\wanlshop\Pay')->get(['order_id' => $id, 'type' => 'goods']);
                // 平台转款给商家
                controller('addons\wanlshop\library\WanlPay\WanlPay')->money(+$pay['price'], $order['shop']['user_id'], '买家确认收货', 'pay', $order['order_no']);
                // 查询是否有退款
                $refund = model('app\api\model\wanlshop\Refund')
                    ->where(['order_id' => $id, 'state' => 4, 'order_type' => 'goods'])
                    ->select();
                // 退款存在
                if ($refund) {
                    foreach ($refund as $value) {
                        controller('addons\wanlshop\library\WanlPay\WanlPay')->money(-$value['price'], $order['shop']['user_id'], '该订单存在的退款', 'pay', $order['order_no']);
                    }
                }
                // 更新退款
                $order->save(['state' => 4, 'taketime' => time()], ['id' => $id]);


                // PeopleSea 线下门店的记录处理

                if ($order->real_store_id) {
                    $ol_money = bcdiv($pay->order_price, 2.2, 2);

                    if ($ol_money > 0 && !OfflineLog::where([
                            'user_id' => $order->user_id,
                            'order_id' => $order->id,
                            'shop_id' => $order->real_store_id
                        ])->find()) {
                        $ol = new OfflineLog([
                            'user_id' => $order->user_id,
                            'order_id' => $order->id,
                            'shop_id' => $order->real_store_id,
                            'money' => $ol_money
                        ]);
                        $result = $ol->save();
                        if ($result === false) throw new Exception('稍后重试');
                    }
                }

                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('ok', $order ? true : false);
        }
        $this->error(__('非法请求'));
    }

    /**
     * 取消订单
     * @return void
     * @throws DbException
     */
    public function cancelOrder()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $id ? $id : ($this->error(__('非法请求')));
            // 判断权限
            $uid = $this->auth->id;
            $row = model('app\api\model\wanlshop\Order')->get(['id' => $id, 'user_id' => $uid]);
            if ($row->state != 1) {
                $this->error(__('订单异常'));
            }
            if ($row->invoice_id > 1) {
                $this->error('订单使用了发票抵扣,不能取消');
            }
            if ($row->offline_order == 1) {
                $this->error('线下实体店订单,不能取消');
            }
            Db::startTrans();
            try {
                $result = $row->allowField(true)->save(['state' => 7]);
                // 还原优惠券 1.0.2升级

                // 释放库存 1.0.3升级
                foreach (model('app\api\model\wanlshop\OrderGoods')->all(['order_id' => $row['id']]) as $vo) {
                    // 查询商品是否需要释放库存
                    if (model('app\api\model\wanlshop\Goods')->get($vo['goods_id'])['stock'] == 'porder') {
                        model('app\api\model\wanlshop\GoodsSku')->where('id', $vo['goods_sku_id'])->setInc('stock', $vo['number']);
                    }
                }

                //回退换购商品
                (new orderModel())->returnBuyback($id, $uid);

                Db::commit();

                //推送第三方
                $third = new Thirdplatform();
                $third->cancel($row->order_no, 'BUYER');

                $this->success('ok', (bool)$result);
            } catch (Exception $e) {
                Db::rollback();
                $this->error('操作失败,' . $e->getMessage());
            }
        }
        $this->error(__('非法请求'));
    }

    /**
     * 删除订单
     *
     * @ApiSummary  (WanlShop 订单接口删除订单)
     * @ApiMethod   (POST)
     *
     * @param string $id 订单ID
     */
    public function delOrder()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $id ? $id : ($this->error(__('非法请求')));
            // 判断权限
            $state = $this->getOrderState($id);
            $state == 6 || $state == 7 ? '' : ($this->error(__('非法请求')));
            $order = model('app\api\model\wanlshop\Order')
                ->save(['status' => 'hidden'], ['id' => $id]);
            $this->success('ok', (bool)$order);
        }
        $this->error(__('非法请求'));
    }


    /**
     * 修改地址
     *
     * @ApiSummary  (WanlShop 订单接口修改地址)
     * @ApiMethod   (POST)
     *
     * @param string $id 订单ID
     */
    public function editOrderAddress()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $order_id = $this->request->post('id');
            $address_id = $this->request->post('address_id');
            $order_id || $address_id ? $order_id : ($this->error(__('非法请求')));
            // 判断权限
            $this->getOrderState($order_id) > 3 ? ($this->error(__('订单异常'))) : '';
            // 订单
            $order = model('app\api\model\wanlshop\Order')
                ->where(['id' => $order_id, 'user_id' => $this->auth->id])
                ->find();

            //判断是否修改过
            if ($order['isaddress'] == 1) {
                $this->error(__('已经修改过一次了'));
            } else {
                // 获取地址
                $address = model('app\api\model\wanlshop\Address')
                    ->where(['id' => $address_id, 'user_id' => $this->auth->id])
                    ->find();
                // 修改地址
                $data = model('app\api\model\wanlshop\OrderAddress')->save([
                    'user_id' => $this->auth->id,
                    'shop_id' => $order->shop_id,
                    'order_id' => $order_id,
                    'isaddress' => 1,
                    'name' => $address['name'],
                    'mobile' => $address['mobile'],
                    'address' => $address['province'] . '/' . $address['city'] . '/' . $address['district'] . '/' . $address['address'],
                    'address_name' => $address['address_name'],
                    'location' => $address['location']
                ]);
                // 修改状态
                model('app\api\model\wanlshop\Order')->where(['id' => $order_id, 'user_id' => $this->auth->id])->update(['isaddress' => 1]);
                $this->success('ok', $data);
            }
        }
        $this->error(__('非法请求'));
    }

    /**
     * 评论订单
     *
     * @ApiSummary  (WanlShop 订单接口评论订单)
     * @ApiMethod   (POST)
     *
     * @param string $id 订单ID
     */
    public function commentOrder()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $post ? $post : ($this->error(__('数据异常')));
            $user_id = $this->auth->id;
            // 判断权限
            $this->getOrderState($post['order_id']) != 4 ? ($this->error(__('已经评论过或订单异常'))) : '';
            // 生成列表
            $commentData = [];
            foreach ($post['goodsList'] as $value) {
                $commentData[] = [
                    'user_id' => $user_id,
                    'shop_id' => $post['shop']['id'],
                    'order_id' => $post['order_id'],
                    'goods_id' => $value['goods_id'],
                    'order_goods_id' => $value['id'],
                    'order_type' => 'goods',
                    'state' => $value['state'],
                    'content' => $value['comment'],
                    'suk' => $value['difference'],
                    'images' => $value['imgList'],
                    'score' => round((($post['shop']['describe'] + $post['shop']['service'] + $post['shop']['deliver'] + $post['shop']['logistics']) / 4), 1),
                    'score_describe' => $post['shop']['describe'],
                    'score_service' => $post['shop']['service'],
                    'score_deliver' => $post['shop']['deliver'],
                    'score_logistics' => $post['shop']['logistics'],
                    'switch' => 0
                ];
                //评论暂不考虑并发，为列表提供好评付款率，减少并发只能写进商品中
                model('app\api\model\wanlshop\Goods')->where(['id' => $value['goods_id']])->setInc('comment');
                if ($value['state'] == 0) {
                    model('app\api\model\wanlshop\Goods')->where(['id' => $value['goods_id']])->setInc('praise');
                } else if ($value['state'] == 1) {
                    model('app\api\model\wanlshop\Goods')->where(['id' => $value['goods_id']])->setInc('moderate');
                } else if ($value['state'] == 2) {
                    model('app\api\model\wanlshop\Goods')->where(['id' => $value['goods_id']])->setInc('negative');
                }
            }
            if (model('app\api\model\wanlshop\GoodsComment')->saveAll($commentData)) {
                $order = model('app\api\model\wanlshop\Order')
                    ->where(['id' => $post['order_id'], 'user_id' => $user_id])
                    ->update(['state' => 6]);
            }
            //更新店铺评分
            $score = model('app\api\model\wanlshop\GoodsComment')
                ->where(['user_id' => $user_id])
                ->select();
            // 从数据集中取出
            $describe = array_column($score, 'score_describe');
            $service = array_column($score, 'score_service');
            $deliver = array_column($score, 'score_deliver');
            $logistics = array_column($score, 'score_logistics');
            // 更新店铺评分
            model('app\api\model\wanlshop\Shop')
                ->where(['id' => $post['shop']['id']])
                ->update([
                    'score_describe' => bcdiv(array_sum($describe), count($describe), 1),
                    'score_service' => bcdiv(array_sum($service), count($service), 1),
                    'score_deliver' => bcdiv(array_sum($deliver), count($deliver), 1),
                    'score_logistics' => bcdiv(array_sum($logistics), count($logistics), 1)
                ]);
            $this->success('ok', []);
        }
        $this->error(__('非法请求'));
    }

    /**
     * 获取订单物流状态
     *
     * @ApiSummary  (WanlShop 订单接口获取订单物流状态)
     * @ApiMethod   (POST)
     *
     * @param string $id 订单ID
     */
    public function getLogistics()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $id ? $id : ($this->error(__('非法请求')));
            //获取订单
            $order = model('app\api\model\wanlshop\Order')
                ->where(['id' => $id, 'user_id' => $this->auth->id])
                ->field('id,shop_id,express_name,express_no,order_no,createtime,paymenttime,delivertime')
                ->find();
            // 获取快递
            switch ($order['state']) {
                case 1:
                    $express[] = [
                        'context' => '付款后，即可将宝贝发出',
                        'status' => '尚未付款',
                        'time' => date('Y-m-d H:i:s', $order['createtime'])
                    ];
                    break;
                case 2:
                    $express[] = [
                        'context' => '商家接受到您的订单，准备出库',
                        'status' => '已下单',
                        'time' => date('Y-m-d H:i:s', $order['paymenttime'])
                    ];
                    break;
                default: // 获取物流
                    // $express = model('app\api\model\wanlshop\KuaidiSub')
                    // 	->where(['express_no' => $order['express_no']])
                    // 	->find();
                    $expModle = new \addons\expressquery\library\Expressquery();
                    $express = $expModle->getExpressList($order['express_name'], $order['express_no']);
                    if ($express) {
                        // $express = json_decode($express['data'], true);
                        $express = $express['data'];
                    } else {
                        $express[] = [
                            'context' => '打包完成，正在等待快递小哥揽收~',
                            'status' => '仓库处理中',
                            'time' => date('Y-m-d H:i:s', $order['delivertime'])
                        ];
                    }
            }
            $order['kuaidi'] = $order->kuaidi ? $order->kuaidi->visible(['name', 'logo', 'tel']) : [];
            $order['express'] = $express;
            $this->success('ok', $order);
        }
        $this->error(__('非法请求'));
    }

    /**
     * 确认订单
     *
     * @ApiSummary  (WanlShop 订单接口确认订单)
     * @ApiMethod   (POST)
     *
     * @param string $data 商品数据
     */
    public function getOrderGoodsList()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $request = $this->request->post();
            $platform = $request['platform'] ?? 0;

            // 订单数据
            $order = array();
            $map = array();

            // 1.0.5升级 修复客户端地址更新
            $where = !empty($request['address_id']) ? [
                'id' => $request['address_id'], 'user_id' => $this->auth->id
            ] : ['user_id' => $this->auth->id, 'default' => 1];
            // 地址
            $address = model('app\api\model\wanlshop\Address')
                ->where($where)
                ->field('id,name,mobile,province,city,district,address')
                ->find();
            if (!$address) {
                $this->error(__('请先添加收货地址'));
            }

            $statis = [
                "allnum" => 0,
                "allsub" => 0
            ];
            $datalist = [
                'token' => self::creatToken(),
                'addressData' => $address,
            ];
            foreach ($request['data'] as $key => $post) {
                $goods = model('app\api\model\wanlshop\Goods')
                    ->where('id', $post['goods_id'])
                    ->find();

                // sku
                $sku = model("app\api\model\wanlshop\GoodsSku")
                    ->where(["id" => $post["sku_id"]])
                    ->find();
                $goods['number'] = $post["number"];
                $goods['sku'] = $sku;
                $statis['allnum'] = isset($statis['allnum']) ? $statis['allnum'] : 0 + $post['number'];
                $statis['allsub'] = bcadd(isset($statis['allsub']) ? $statis['allsub'] : 0, $post['c_original_price'] ?? 0, 2);
                $goods['return'] = isset($goods['shop_goods']) ? $goods['shop_goods']['return'] : [];;

                // 1.1.2升级 判断是否超出库存
                $sku_key = 'goods_' . $sku['goods_id'] . '_' . $sku['id'];
                // if($post['number'] > $redis->llen("{$sku_key}")){
                if ($post['number'] > $sku['stock']) {
                    $this->error("系统繁忙，请稍后抢购！");
                }
                // 获取快递及价格
//                if (isset($post['platform']) && $post['platform'] == 0) {
//                    $goods['freight'] = $this->freight($goods['freight_id'], $sku['weigh'], $post['number'], $address['city']);
//                } else {
                $goods['freight'] = [];
//                }

                if (empty($map[$goods['shop_id']])) {
                    $order[] = array(
                        "shop_id" => $goods['shop_id'],
                        "shop_name" => $goods->shop_goods ? $goods->shop_goods->visible(['shopname'])['shopname'] : [],
                        "products" => [$goods],
                        "coupon" => [],
                        "freight" => $goods['freight'] ? [$goods['freight']] : null,
                        "number" => $goods['number'],
                        "sub_price" => bcmul($sku['price'], $goods['number'], 2),
                        'platform' => $post['platform'] ?? 0,
                    );
                    $map[$goods['shop_id']] = $goods;
                } else {
                    // 追加1-*
                    foreach ($order as $k => $v) {
                        if ($v['shop_id'] == $goods['shop_id']) {
                            $order[$k]['products'][] = $goods;
                            $order[$k]['freight'][] = $goods['freight'];
//                            array_push($order[$k]['products'], $goods);
//                            array_push($order[$k]['freight'], $goods['freight']);
                            $order[$k]['number'] += $post['number'];
                            $order[$k]['sub_price'] = bcadd($order[$k]['sub_price'], bcmul($sku['price'], $post['number'], 2), 2);
                            break;
                        }
                    }
                }
                // 所有店铺统计
                $statis['allnum'] += $goods['number'];
            }


            // 订单
            /*$res['orderData']['statis'] = $statis;
            $res['orderData']['lists'] = $order;
            $this->success('ok', $res);*/

            // 来自唯品尚
            /*if ($platform == 1) {
                // 传递Token
                $datalist['token'] = self::creatToken();
                // 地址
                $datalist['addressData'] = $address;
                $statis = [];
                $order = [];
                foreach ($request['data'] as $key => $post) {
                    // 商品
                    $goods = model('app\api\model\wanlshop\Goods')
                        ->where('id', $post['goods_id'])
                        ->field('id, shop_id, shop_category_id, activity_type, title,image,stock,freight_id,sales,c_id,c_father_goods_id, c_original_price, c_goods_stock_valid, c_goods_stock_start')
                        ->find();

                    // sku
                    $goodsSku = model("app\api\model\wanlshop\GoodsSku")
                        ->where(["id" => $post["sku_id"]])
                        ->find();

                    $goods["number"] = $post["number"];
                    $goods["sku"] = $goodsSku;
                    $statis['allnum'] = isset($statis['allnum']) ? $statis['allnum'] : 0 + $post['number'];
                    $statis['allsub'] = bcadd(isset($statis['allsub']) ? $statis['allsub'] : 0, $post['c_original_price'] ?? 0, 2);
                    $order[$key]['products'][] = $goods;
                }

                // 订单
                $datalist['orderData']['statis'] = $statis;
                $datalist['orderData']['lists'] = $order;
                $this->success('ok', $datalist);
            }*/

            // 合计
            /*$statis = array(
                "allnum" => 0,
                "allsub" => 0
            );
            foreach ($request['data'] as $post) {
                //$redis = Common::redis();
                // 商品详情
                $goods = model('app\api\model\wanlshop\Goods')
                    ->where('id', $post['goods_id'])
                    ->field('id, shop_id, shop_category_id, activity_type, title,image,stock,freight_id,sales,platform')
                    ->find();
                // 获取SKU
                $sku = model('app\api\model\wanlshop\GoodsSku')
                    ->where('id', $post['sku_id'])
                    ->field('id,goods_id,difference,price,market_price,stock,weigh')
                    ->find();

                // 1.1.2升级 判断是否超出库存
                $sku_key = 'goods_' . $sku['goods_id'] . '_' . $sku['id'];
                // if($post['number'] > $redis->llen("{$sku_key}")){
                if ($post['number'] > $sku['stock']) {
                    $this->error("系统繁忙，请稍后抢购！");
                }
                // 获取快递及价格
                if ($platform == 0) {
                    $goods['freight'] = $this->freight($goods['freight_id'], $sku['weigh'], $post['number'], $address['city']);
                } else {
                    $goods['freight'] = [];
                }
                // 获取SKU
                $goods['sku'] = $sku;
                // 数量
                $goods['number'] = $post['number'];
                $goods['return'] = $goods->shop_goods ? $goods->shop_goods->visible(['return'])['return'] : '';
                // 格式化
                if (empty($map[$goods['shop_id']])) {
                    $order[] = array(
                        "shop_id" => $goods['shop_id'],
                        "shop_name" => $goods->shop_goods ? $goods->shop_goods->visible(['shopname'])['shopname'] : [],
                        "products" => [$goods],
                        "coupon" => [],
                        "freight" => [$goods['freight']],
                        "number" => $goods['number'],
                        "sub_price" => bcmul($sku['price'], $goods['number'], 2)
                    );
                    $map[$goods['shop_id']] = $goods;
                } else {
                    // 追加1-*
                    foreach ($order as $key => $value) {
                        if ($value['shop_id'] == $goods['shop_id']) {
                            array_push($order[$key]['products'], $goods);
                            array_push($order[$key]['freight'], $goods['freight']);
                            $order[$key]['number'] += $post['number'];
                            $order[$key]['sub_price'] = bcadd($order[$key]['sub_price'], bcmul($sku['price'], $post['number'], 2), 2);
                            break;
                        }
                    }
                }
                // 所有店铺统计
                $statis['allnum'] += $goods['number'];
            }*/

            // 获取运费策略-店铺循环
            /*foreach ($order as $key => $value) {
                if (isset($value['platform']) && $value['platform'] == 1) {
                    continue;
                }
                if (empty($value['freight'])) {
                    continue;
                }
                if (is_array($value['freight']) && empty(array_unique(get_object_vars($value['freight'][0])))) {
                    continue;
                }
                if (is_array($value['freight']) && empty(array_unique($value['freight'][0]))) {
                    continue;
                }
                $config = model('app\api\model\wanlshop\ShopConfig')
                    ->where('shop_id', $value['shop_id'])
                    ->find();
                if ($config) {
                    if ($config['freight'] == 0) {
                        // 运费叠加
                        $order[$key]['freight'] = [
                            'id' => $value['freight'][0]['id'] ?? 0,
                            'name' => '运费叠加',
                            'price' => isset($value['freight']) ? array_sum(array_column($value['freight'], 'price')) : 0
                        ];
                    } else if ($config['freight'] == 1) {
                        // 以最低结算
                        array_multisort(array_column($value['freight'], 'price'), SORT_ASC, $value['freight'] ?? 0);
                        $order[$key]['freight'] = [
                            'id' => $value['freight'][0]['id'] ?? 0,
                            'name' => $value['freight'][0]['name'] ?? '',
                            'price' => $value['freight'][0]['price'] ?? 0
                        ];
                    } else if ($config['freight'] == 2) {
                        // 以最高结算
                        array_multisort(array_column($value['freight'] ?? 0, 'price'), SORT_DESC, $value['freight'] ?? 0);
                        $order[$key]['freight'] = [
                            'id' => $value['freight'][0]['id'] ?? 0,
                            'name' => $value['freight'][0]['name'] ?? '',
                            'price' => $value['freight'][0]['price'] ?? 0
                        ];
                    }
                    $order[$key]['order_price'] = $order[$key]['sub_price'];
                    // 2020年9月19日12:10:59 添加快递价格备份,用于还原运费
                    $order[$key]['freight_price_bak'] = $order[$key]['freight']['price'];
                    // 1.0.8升级
                    $order[$key]['sub_price'] = bcadd($order[$key]['sub_price'], $order[$key]['freight']['price'], 2);
                    $statis['allsub'] = bcadd($statis['allsub'], $order[$key]['sub_price'], 2);
                } else {
                    $this->error(__('商家未配置运费组策略，暂不支持下单'));
                }
            }*/

            // 订单
            $datalist['orderData']['lists'] = $order;
            $datalist['orderData']['statis'] = $statis;
            $datalist['invoice'] = \app\common\model\User::where('id', $this->auth->id)->value('invoice');
            $datalist['buyback'] = get_addon_config('wanlshop')['gift'];
            $this->success('ok', $datalist);
        } else {
            $this->error(__('非法请求'));
        }
    }

    /**
     * 提交订单（下单，正常购买）
     * @ApiSummary  (WanlShop 订单接口提交订单)
     * @ApiMethod   (POST)
     *
     * @param string $data 数组
     * @throws \Exception
     */
    public function addOrder()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        if ($this->request->isPost()) {
            $result = false;
            $params = $this->request->post();
            Log::log("下单参数:" . json_encode($params, 256));

            // 验证Token
            if (array_key_exists('token', $params)) {
                if (!self::checkToken($params['token'])) {
                    $this->error(__('请勿重复提交订单'));
                }
            } else {
                $this->error(__('非法提交，未传入Token'));
            }
            $user_id = $this->auth->id; // 用户ID
            $addressList = [];
            $goodsList = [];
            $payList = [];

            $real_store_id = isset($params['order']['real_store_id']) && $params['order']['real_store_id'] ? $params['order']['real_store_id'] : 0;

            // 判断是否有地址 1.0.2升级
            if (array_key_exists('address_id', $params['order'])) {
                $address_id = $params['order']['address_id']; // 地址ID
            } else {
                $this->error(__('请点击上方添加收货地址'));
            }

            // 判断订单是否合法 1.0.4升级
            if (array_key_exists('lists', $params['order'])) {
                $lists = $params['order']['lists'];
                if (!isset($lists) && count($lists) == 0) {
                    $this->error(__('订单繁忙ERR001：请返回商品详情重新提交订单'));
                }
            } else {
                $this->error(__('订单繁忙ERR002：请返回商品详情重新提交订单'));
            }

            // 查询地址
            $address = model('app\api\model\wanlshop\Address')
                ->where(['id' => $address_id, 'user_id' => $user_id])
                ->find();
            // 1.0.4升级
            if (!isset($address)) {
                $this->error(__('地址异常，没有找到该地址'));
            }
            $user = \app\common\model\User::find($user_id);

            bcscale(2);
            $redis = Common::redis();

            // 数据库事务操作
            Db::startTrans();
            try {
                // 查询商品
                $goodsDict = model('app\api\model\wanlshop\Goods')
                    ->where('id', 'in', array_column($params['order']['lists'], 'goods_id'))
                    ->column('shop_id,stock,freight_id,title,image,integral,c_father_goods_id,platform', 'id');
                if (!$goodsDict) {
                    $this->error(__('商品数据不存在'));
                }

                $data = $params['order'];
//                foreach ($params['order'] as $ord) {
                foreach ($data['lists'] as $v) {
                    if (!isset($v['goods_id']) || !isset($v['platform']) || !isset($v['sku_id']) || !isset($v['shop_id'])) {
                        $this->error('新商品缺少参数');
                    }
                    // 获取店铺ID
                    $shop_id = $v['shop_id'];
                    // 查询店铺配置
                    $config = model('app\api\model\wanlshop\ShopConfig')
                        ->where('shop_id', $shop_id)
                        ->find();
                }

                // 如果不存在，按照累计运费
                if (empty($config)) {
                    $config['freight'] = 0;
                }
                $shop_id = isset($shop_id) && !empty($shop_id) ? $shop_id : 0;
                $pointsInfo = [];
                if (!empty($params['order']['pointsinfo'])) {
                    $pointsInfo = $params['order']['pointsinfo'];
                }

                // 生成订单
                $images = '';
                if (!empty($params['order']['images'])) {
                    if (is_array($params['order']['images'])) {
                        $images = implode(',', $params['order']['images']);
                    } elseif (is_string($params['order']['images'])) {
                        $images = $params['order']['images'];
                    }
                } elseif (!empty($params['order']['QualificationsImgList'])) {
                    if (is_array($params['order']['QualificationsImgList'])) {
                        $images = implode(',', $params['order']['QualificationsImgList']);
                    } elseif (is_string($params['order']['QualificationsImgList'])) {
                        $images = $params['order']['QualificationsImgList'];
                    }
                }
                Log::log("imgs:" . $images);
                $order_no = $shop_id . $user_id . mt_rand(100000, 999999);
                Log::log("下单订单号:" . $order_no);
                $order = new orderModel;
                $order->freight_type = $config['freight'];
                $order->user_id = $user_id;
                $order->shop_id = $shop_id;
                $order->real_store_id = $real_store_id;
                $order->score = $pointsInfo['score'] ?? 0;
                $order->score_price = $pointsInfo['price'] ?? 0;
                $order->offline_order = $params['order']['offline_order'] ?? 0;
                $order->invoice_id = $params['order']['invoice_id'] ?? 0;
                $order->address_id = $params['order']['address_id'] ?? 0;
                $order->order_no = $order_no;
                $order->order_type = $params['order']['order_type']; // 订单类型 0 正常订单 1 换购订单 2图片换购
                $order->tracking_number = !empty($params['order']['tracking_number']) ? $params['order']['tracking_number'] : ''; // 物流单号
                $order->images = $images;
                $order->state = empty($params['order']['images']) ? 1 : 8;//1待支付，8待审核
                $order->flag = $params['flag'] ?? 0;
                $order->remarks = $params['order']['remarks'] ?? '';

                // 2021年3月04日 06:54:11 修改优惠券逻辑
                $coupon = model('app\api\model\wanlshop\CouponReceive')
                    ->where(['id' => $params['order']['coupon_id'] ?? 0, 'user_id' => $user_id, 'shop_id' => $shop_id])
                    ->find();
                $order->coupon_id = $coupon ? $coupon['id'] : 0;

                $res = $order->save();
                Log::log("下单参数res:" . json_encode($order, 256));
                if ($res === false) {
                    $this->error('网络繁忙，创建订单失败！');
                }

                $priceAll = 0; // 总价格
                $numberAll = 0; // 总数量
                $invoicePrice = 0;//发票抵扣金额
                $score = 0; // 积分
                $freightALL = [];
                $shopGoodsAll = [];

                // 计算订单价格
                $goodInfo = [];
                foreach ($data['lists'] as $item) {
                    $goods = $goodsDict[$item['goods_id']] ?? [];

                    // 获取sku
                    $sku = GoodsSku::where('id', $item['sku_id'])->find();
                    if (!$sku) {
                        $this->error('商品SKU数据不存在');
                    }

                    // 1.1.2升级
                    $sku_key = 'goods_' . $sku['goods_id'] . '_' . $sku['id'];

                    // 效验shop_id是否正确 1.1.2升级
                    $shop_id = $goods['shop_id'];
                    if ($item['shop_id'] != $goods['shop_id']) {
                        $this->error('网络异常SHOPID错误');
                    }

                    // 1.1.2升级 提交订单判断库存
                    $number = $item['number'] ?? 1;
                    if ($sku['stock'] <= 0) {
                        $this->error('商品被抢光了');
                    } else if ($sku['stock'] < $number) {
                        $this->error('库存不足');
                    }

                    // 库存计算方式:porder=下单减库存,payment=付款减库存
                    if ($goodsDict[$item['goods_id']]['stock'] == 'porder') {
                        // 1.1.2升级
                        // if($number > $redis->llen("{$sku_key}")){
                        if ($number > $sku['stock']) {
                            $this->error('系统繁忙，请稍后抢购！');
                        } else {
                            for ($i = 0; $i < $number; $i++) {
                                $redis->rpop("{$sku_key}");
                            }
                            $sku->setDec('stock', $number); // 1.0.3升级
                        }
                    }

                    if ($goods['platform'] == 1) {
                        $goodInfo[] = [
                            'goodSpecId' => $sku["wps_goods_id"],
                            'goodsId' => $sku["wps_father_goods_id"] ?? 0,
                            'num' => $number,
                        ];
                    }

                    // 东火木商家商品,生成运费
                    $freight = [];
                    $platform = $goodsDict[$item['goods_id']]['platform'] ?? 0;
                    /*if ($platform == 0) {
                        $freight = $this->freight($goodsDict[$item['goods_id']]['freight_id'], $sku['weigh'], $number, $address['city']);
                        $freightALL[] = $freight;
                    }*/

                    // 商品列表 actual_payment
                    $orderId = intval($order->id);
                    $shopGoodsAll[] = [
                        'order_id' => $orderId, // 获取自增ID
                        'goods_id' => $item['goods_id'],
                        'shop_id' => $shop_id,
                        'user_id' => $user_id,
                        'title' => $goodsDict[$item['goods_id']]['title'] ?? '',
                        'image' => $goodsDict[$item['goods_id']]['image'] ?? '',
                        'goods_sku_sn' => $sku['sn'],
                        'goods_sku_id' => $sku['id'],
                        'difference' => join(',', $sku['difference']),
                        'market_price' => $sku['market_price'], // 市场价
                        'price' => $sku['price'], // 原价
                        'freight_price' => 0, //快递价格
                        'discount_price' => 0, // 优惠金额
                        'actual_payment' => bcmul($sku['price'], $number), // 1.0.6修复 实际支付，因为要和总价进行计算
                        'number' => $number,
                        'original_order_id' => $orderId,
                        'type' => 'new'
                    ];

                    $priceAll = bcadd($priceAll, bcmul($sku['price'], $number)); // 计算价格

                    //订单类型 0 正常订单 1 换购订单 2图片换购
                    if (!empty($params['order']['order_type'] && $params['order']['order_type'] > 0)) {
                        if ($priceAll > 50) {
                            /*if ($images == '') {
                                $this->error('请上传旧物图片');
                            }
                            if (empty($params['order']['tracking_number'])) {
                                $this->error('请填写物流单号');
                            }*/
                        }
                    }

                    //换购倍数
                    $configGift = get_addon_config('wanlshop');
                    $multiple = $configGift['gift']['mulriple'] ?? 0;
                    //gift想换的新东西,priceAll旧物 5
                    $new = array_sum(array_column($params['order']['gift'], 'price'));
                    $old = bcmul($priceAll, $multiple);
                    /*if ($old > $new) {
                        Log::info("新商品总价:$new,旧物价格:$old,倍数:$multiple");
                        CommmonService::error("要换购的商品的价格必须大于原商品的 $multiple 倍");
                    }*/

                    $numberAll += $number; // 计算数量
                    $score += $goodsDict[$item['goods_id']]['integral'] ?? 0; // 计算积分
                }
                Log::log("goods_info:" . json_encode($goodInfo, 256));

                // 给第三方平台同步订单
                if ($goodInfo) {
                    $thr_order = [
                        'lockCode' => $order_no,
                        'consigneeContacts' => $address['name'],
                        'consigneePhone' => $address['mobile'],
                        'province' => $address['province'],
                        'city' => $address['city'],
                        'area' => $address['district'],
                        'address' => $address['address'],
                        'source' => 'DONGHUOMU',
                        'goodInfo' => json_encode($goodInfo, 256)
                    ];
                    Log::log("ins_order_before11:" . json_encode($thr_order, 256));
//                    $res = $this->thrService->insOrder($thr_order);
                    $res = $this->thrService->insBatchOrder($thr_order);
                    Log::log("ins_order_res:" . $res);
                    $res = json_decode($res, 256);
                    if (!isset($res['code']) || $res['code'] != 0) {
                        $this->error($res['msg'] ?? '');
                    }
                }

                //图片回购，抵扣40%
                $price = $priceAll;
                $system_price = 0;
                if (isset($params['order']['order_type']) && $params['order']['order_type'] == 2) {
                    $price = bcmul($price, 0.6, 2);
                    $system_price = bcmul($priceAll, 0.4, 2);
                }

                //发票抵扣
                if (isset($params['order']['invoice_id']) && $params['order']['invoice_id'] > 0) {
                    $invoice = Invoice::where(['id' => $params['order']['invoice_id'], 'uid' => $user->id, 'sh' => 1])->find();
                    if (!$invoice) {
                        $this->error('发票不存在');
                    }
                    $invoicePrice = $invoice->price;
                    UserFinanceLog::addRecord([[
                        'user_id' => $user->id,
                        'type' => 'invoice',
                        'flag' => 'reduce',
                        'value' => $invoicePrice,
                        'before' => $user->invoice,
                        'after' => bcsub($user->invoice, $invoicePrice),
                        'event' => 'pay',
                        'remark' => "$order_no",
                        'rel_id' => $orderId,
                        'status' => 'succeed',
                    ]]);
                    $price = bcsub($price, $invoicePrice);
                    $user->invoice = bcsub($user->invoice, $invoicePrice);
                    $user->save();

                    $invoice->sh = 3;
                    $invoice->save();
                }

                // 计算运费叠加方案,图片换购包邮
                if (isset($params['order']['order_type']) && in_array($params['order']['order_type'], [0, 1])) {
                    /*if (isset($config) && $config['freight'] == 0) {
                        // 运费叠加
                        $freight = [
                            'id' => $freightALL[0]['id'] ?? 0,
                            'name' => '合并运费',
                            'price' => array_sum(array_column($freightALL, 'price'))
                        ];
                    } else if (isset($config) && $config['freight'] == 1) { // 以最低结算
                        array_multisort(array_column($freightALL, 'price'), SORT_ASC, $freightALL);
                        $freight = [
                            'id' => $freightALL[0]['id'] ?? 0,
                            'name' => $freightALL[0]['name'] ?? '',
                            'price' => $freightALL[0]['price'] ?? 0
                        ];
                    } else if (isset($config) && $config['freight'] == 2) { // 以最高结算
                        array_multisort(array_column($freightALL, 'price'), SORT_DESC, $freightALL);
                        $freight = [
                            'id' => $freightALL[0]['id'] ?? 0,
                            'name' => $freightALL[0]['name'] ?? '',
                            'price' => $freightALL[0]['price'] ?? 0
                        ];
                    }*/
                }

                $freight_price = 0;  //快递金额
                $price = bcadd($price, $freight_price, 2); // 总价格
                $coupon_price = 0; //优惠券金额
                $discount_price = 0; // 优惠金额，因为后续版本涉及到活动减免，所以优惠金额要单独拎出来

                // 如果优惠券存在
                if ($coupon) {
                    // 判断是否可用
                    if ($priceAll >= $coupon['limit']) {
                        // 优惠金额
                        if ($coupon['type'] == 'reduction' || ($coupon['type'] == 'vip' && $coupon['usertype'] == 'reduction')) {
                            $coupon_price = $coupon['price'];
                            //总金额 =（订单金额 - 优惠券金额）+ 运费
                            $price = bcadd(bcsub($priceAll, $coupon_price), $freight['price'] ?? 0, 2);
                        }
                        // 折扣金额
                        if ($coupon['type'] == 'discount' || ($coupon['type'] == 'vip' && $coupon['usertype'] == 'discount')) {
                            // 排除异常折扣，还原百分之
                            $discount = $coupon['discount'] > 10 ? bcdiv($coupon['discount'], 100) : bcdiv($coupon['discount'], 10, 2);
                            // 优惠金额 = 订单金额 - 订单金额 * 折扣
                            $coupon_price = bcsub($priceAll, bcmul($priceAll, $discount));
                            $price = bcadd(bcsub($priceAll, $coupon_price), $freight['price'] ?? 0);
                        }
                        // 免邮金额
                        if ($coupon['type'] == 'shipping') {
                            $coupon_price = $freight_price;
                            $price = $priceAll;
                            $freight_price = 0;
                        }
                        $discount_price = $coupon_price;

                        // 总优惠金额 1.1.3弃用
                        // $paycoupon = 0;
                        // 总实际支付金额 1.1.3弃用
                        // $payment = 0;
                        foreach ($shopGoodsAll as $row) {
                            $goods_price = bcmul($row['price'], $row['number']);
                            $goods_discount_price = round($coupon_price * ($goods_price / $priceAll)); // 优惠金额
                            // 1.0.8升级,修复包邮
                            $actual_payment = $coupon['type'] === 'shipping' ? $goods_price : bcsub($goods_price, $goods_discount_price, 2);
                            //优惠价格
                            $row['discount_price'] = $goods_discount_price;
                            // 实际支付 1.0.9升级
                            $row['actual_payment'] = $actual_payment <= 0 ? '0.01' : $actual_payment;
                            $row['freight_price'] = $freight_price;
                            // 1.0.8升级 1.1.3弃用
                            // $paycoupon = bcadd($paycoupon, $goods_discount_price, 2);
                            // $payment = bcadd($payment, $actual_payment, 2);
                            $goodsList[] = $row;
                        }

                        // 更新已使用数量
                        model('app\api\model\wanlshop\Coupon')
                            ->where(['id' => $coupon['coupon_id']])
                            ->setInc('usenum');
                        // 修改该优惠券状态 已用
                        $coupon->allowField(true)->save(['state' => 2]);
                    } else {
                        model('app\api\model\wanlshop\Order')->destroy($order->id);
                        throw new Exception('订单金额' . $priceAll . '元，不满' . $coupon['limit'] . '元');
                    }
                } else {
                    foreach ($shopGoodsAll as $row) {
                        $goodsList[] = $row;
                    }
                }

                //积分抵扣
                if ($params['order']['is_score']) {
                    $price = bcsub($price, $pointsInfo['price']);
                }

                //选择了旧物抵扣
                $giftPrice = 0;
                if ($params['order']['gift']) {
                    $paramsGift = $params['order']['gift'];
                    $goodsDict = Goods::where('id', 'in', array_column($paramsGift, 'goods_id'))->column('shop_id,title,image', 'id');
                    $skuDict = GoodsSku::where('id', 'in', array_column($paramsGift, 'sku_id'))->column('id,sn,difference,market_price,price', 'id');
                    /*if (count($goodsDict) != count($paramsGift) || count($skuDict) != count($paramsGift)) {
                        $this->error('选择的旧物数量不匹配');
                    }*/

                    //状态变更为已换购
                    if ($params['order']['order_type'] == 1) {
                        $orderGoodsModel = new OrderGoods();
                        $ids = array_column($paramsGift, 'original_order_id');
                        $goods_ids = array_column($paramsGift, 'goods_id');
                        $orderGoodsModel
                            ->where([
                                'original_order_id' => ['in', $ids],
                                'goods_id' => ['in', $goods_ids],
                                'user_id' => $user_id
                            ])
                            ->update(['is_buyback' => 1]);
                    }

                    foreach ($paramsGift as $item) {
                        if (empty($item['goods_id'])) {
                            $this->error('缺少旧物参数goods_id');
                        }
                        if (empty($item['sku_id'])) {
                            $this->error('缺少旧物参数sku_id');
                        }
                        if (empty($item['original_order_id'])) {
                            $this->error('缺少旧物参数original_order_id');
                        }
                        $original_order_id = $item['original_order_id'] ?? 0;
                        $original_goods_id = OrderGoods::where(['order_id' => $original_order_id, 'user_id' => $user_id, 'goods_id' => $item['goods_id']])->value('id');
                        $tempPrice = $skuDict[$item['sku_id']]['price'] ?? 0;
                        $goodsList[] = [
                            'order_id' => $orderId, // 获取自增ID
                            'goods_id' => $item['goods_id'],
                            'shop_id' => $goodsDict[$item['goods_id']]['shop_id'] ?? 0,
                            'user_id' => $user_id,
                            'title' => $goodsDict[$item['goods_id']]['title'],
                            'image' => $goodsDict[$item['goods_id']]['image'],
                            'goods_sku_sn' => $skuDict[$item['sku_id']]['sn'] ?? '',
                            'goods_sku_id' => $skuDict[$item['sku_id']]['id'] ?? 0,
                            'difference' => $skuDict[$item['sku_id']]['difference'] ?? '',
                            'market_price' => $skuDict[$item['sku_id']]['market_price'] ?? 0, // 市场价
                            'price' => $tempPrice, // 原价
                            'freight_price' => 0, //快递价格
                            'discount_price' => 0, // 优惠金额
                            'actual_payment' => 0, // 1.0.6修复 实际支付，因为要和总价进行计算
                            'number' => 1,
                            'original_order_id' => $original_order_id,
                            'original_goods_id' => $original_goods_id,
                            'type' => 'old'
                        ];
                        $giftPrice = bcadd($giftPrice, $tempPrice, 2);
                        $price = bcsub($price, $tempPrice, 2);
                    }
                }

                // 生成支付
                $payList[] = [
                    'user_id' => $user_id,
                    'shop_id' => $shop_id,
                    'order_id' => $orderId,
                    'order_no' => $order_no,
                    'pay_no' => $order_no,
                    'type' => 'goods', // 1.0.8升级
                    'price' => $price <= 0 ? 0.01 : $price,  // 支付价格，系统要求至少支付一分钱
                    'order_price' => $priceAll, // 订单总金额
                    'score_price' => $pointsInfo['price'] ?? 0, // 积分抵扣价格
                    'system_price' => $system_price ?? 0,//图片抵扣优惠金额
                    'invoice_price' => $invoicePrice,//发票抵扣金额
                    'oldstaff_price' => $giftPrice,//旧物价格
                    'coupon_price' => $coupon_price,  // 优惠券金额
                    'freight_price' => $freight_price, // 快递费
                    'discount_price' => $discount_price, // 优惠金额
                    'number' => $numberAll
                ];

                //生成分销记录
                $this->divideHandle($orderId, $user_id, $shop_id, $real_store_id, $price);

//                var_dump($payList);
//                throw new Exception('cuowu');
                // 生成地址
                $addressList[] = [
                    'user_id' => $user_id,
                    'shop_id' => $shop_id,
                    'order_id' => $orderId,
                    'name' => $address['name'],
                    'mobile' => $address['mobile'],
                    'address' => $address['province'] . '/' . $address['city'] . '/' . $address['district'] . '/' . $address['address'],
                    'address_name' => $address['address_name'],
                    'location' => $address['location'],
                    "shop_address" => $params["order"]["shop_address"] ?? "",
                    "shop_username" => $params["order"]["shop_username"] ?? "",
                    "shop_mobile" => $params["order"]["shop_mobile"] ?? ""
                ];
//                }

                // 积分添加
                /*$this->userModel->addingUserCredits(['id' => $user_id], $score, 'sys', $orderId);
                if ($pointsInfo) {
                    $user = \app\admin\model\User::find($user_id);
                    UserFinanceLog::addRecord([[
                        'user_id' => $user_id,
                        'admin_id' => 0,
                        'type' => 'score',
                        'flag' => 'reduce',
                        'value' => $pointsInfo['score'],
                        'before' => $user->score,
                        'after' => bcadd($user->score, $pointsInfo['score'], 2),
                        'event' => 'pay',
                        'rel_id' => $orderId,
                        'status' => 'succeed',
                        'createtime' => time(),
                        'updatetime' => time()
                    ]]);
                    $user->score = bcsub($user->score, $pointsInfo['score'], 2);
                    $user->save();
                }*/

                // 添加活动返现记录
                if (!empty($params['order']['act']) && $params['order']['order_type'] == 2) {
                    $cashModel = $this->withdrawalCashModel;
                    if (empty($params['order']['act']['act_available_time']) || empty($params["order"]["act"]["amount_withdrawal"])) {
                        $this->error('活动返现参数错误');
                    }
                    $act = [];
                    $act["createtime"] = time();
                    $act["act_available_time"] = $params['order']['act']['act_available_time'] ?? 0;
                    $act["amount_withdrawal"] = $params["order"]["act"]["amount_withdrawal"] ?? 0;
                    $act["w_type"] = 3;
                    $act["user_id"] = $this->auth->id;
                    $this->actCashBackService->insWithdrawalRecord($act);
                }

                model('app\api\model\wanlshop\OrderAddress')->saveAll($addressList);
                model('app\api\model\wanlshop\OrderGoods')->saveAll($goodsList);
                $result = model('app\api\model\wanlshop\Pay')->saveAll($payList);
                Db::commit();
                if ($params['order']['order_type'] === 0) { // 正常订单
                    // 把订单存到redis
                    $orderInfo = array(
                        "order_no" => $order_no,
                        "user_id" => $user_id,
                        "order_id" => $orderId,
                        "createtime" => $order->createtime
                    );
                    // 判断key值是否存在，存在追加，不存在添加
                    if ($redis->exists("order_no_pay")) {
                        $redis->rPushx("order_no_pay", json_encode($orderInfo));
                    } else {
                        $redis->rPush("order_no_pay", json_encode($orderInfo));
                    }
                }
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage() . ',Line:' . $e->getLine());
            }
            if ($result !== false) {
                $this->success('返回成功', ['list' => $result, 'token' => self::creatToken()]);
            } else {
                $this->error(__('订单异常，请返回重新下单'));
            }
        } else {
            $this->error(__('非法请求'));
        }
    }

    /**
     * 订单状态码（方法内使用）
     *
     * @ApiSummary  (WanlShop 返回订单状态码)
     * @ApiMethod   (POST)
     *
     * @param string $id 订单ID
     */
    private function getOrderState($id = 0)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        return model('app\api\model\wanlshop\Order')->where('id', $id)->value('state');
    }

    /**
     * 获取运费模板和子类 内部方法
     * @param string $id 运费ID
     * @param string $weigh 商品重量
     * @param string $number 商品数量
     * @param string $city 邮递城市
     */
    private function freight($id = null, $weigh = null, $number = 0, $city = null)
    {
//	    echo $city;exit;
        // 运费模板
        $data = model('app\api\model\wanlshop\ShopFreight')
            ->where('id', $id)
            ->field('id,delivery,isdelivery,name,valuation')
            ->find();
        if (!$data) {
            $this->error(__('此商品运费模板不存在，暂不支持下单'));
        }
        $data['price'] = 0;
        // 是否包邮:0=自定义运费,1=卖家包邮
        if ($data['isdelivery'] == 0) {
            // 获取地址编码 1.1.0升级
            $list = model('app\api\model\wanlshop\ShopFreightData')
                ->where([
                    ['EXP', Db::raw('FIND_IN_SET(' . model('app\common\model\Area')->get(['name' => $city])->id . ', citys)')],
                    'freight_id' => $id
                ])
                ->find();
            // 查询是否存在运费模板数据
            if (!$list) {
                $list = model('app\api\model\wanlshop\ShopFreightData')->get(['freight_id' => $id]);
            }

            // 计价方式:0=按件数,1=按重量,2=按体积  1.0.2升级
            if ($data['valuation'] == 0) {
                if ($number <= $list['first']) {
                    $price = $list['first_fee'];
                } else {
                    $additional = $list['additional'] > 0 ? $list['additional'] : 1; //因为要更换vue后台，临时方案，为防止客户填写0
                    $price = bcadd(bcmul(ceil(($number - $list['first']) / $additional), $list['additional_fee'], 2), $list['first_fee'], 2);
                }
            } else {
                $weigh = $weigh * $number; // 订单总重量
                if ($weigh <= $list['first']) { // 如果重量小于等首重，则首重价格
                    $price = $list['first_fee'];
                } else {
                    $additional = $list['additional'] > 0 ? $list['additional'] : 1;
                    $price = bcadd(bcmul(ceil(($weigh - $list['first']) / $additional), $list['additional_fee'], 2), $list['first_fee'], 2);
                }
            }
            $data['price'] = $price;
        }
        return $data;
    }

    /**
     * 创建Token
     */
    private function creatToken()
    {
        $code = chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE)) . chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE)) . chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE));
        $key = "WANLSHOP.COM";
        $code = md5($key . substr(md5($code), 8, 10));
        Cache::set('orderToken', $code, 180);
        return $code;
    }

    /**
     * 验证Token
     * @param {Object} $token
     */
    private function checkToken($token)
    {
        if ($token == Cache::get('orderToken')) {
            Cache::set('orderToken', NULL);
            return TRUE;
        } else {
            return FALSE;
        }
    }

    private function divideHandle($order_id, $user_id, $shop_id, $real_store_id, $price)
    {
        Log::log("divideHandle-->order_id:$order_id, user_id:$user_id, shop_id:$shop_id, real_store_id:$real_store_id, price:$price");
        $time = date('Y-m-d H:i:s');
        $userShare = UserShare::where('user_id', $user_id)->find();
        $config = get_addon_config('wanlshop');
        $config = $config['agent'];
        $share_a = Share::where(['user_id' => $user_id])->find();
        if ($share_a) {
            $share = Share::find($share_a['parent_id']);
        } else {
            $share = Share::where('user_id', $userShare['parent_id'] ?? 0)->find();
        }
        Log::log('share data:' . json_encode($share, 256));
        if ($share) {
            $order = \app\admin\model\wanlshop\Order::find($order_id);
            $shareModel = new ShareOrder();
            $parent_amount = $p_parent_amount = 0;
            if ($config["share{$share['level']}"]) {
                $parent_amount = bcdiv(bcmul($config["share{$share['level']}"], $price, 4), 100, 2);
            }
            Log::log("分销数据:order_id:$order_id,user_id:$user_id,config:" . json_encode($config, 256));
            $data[] = [
                'user_id' => $user_id,
                'order_id' => $order_id,
                'shop_id' => $shop_id,
                'pay_amount' => $price,
                'parent_user_id' => $share['user_id'],
                'parent_share_id' => $share['id'],
                'parent_level' => $share['level'],
                'parent_amount' => $parent_amount,
                'created_at' => $time,
                'updated_at' => $time,
                'order_sn' => date('YmdHis') . mt_rand(100000, 999999)
            ];

            $p_share = Share::find($share['parent_id']);
            Log::log($p_share);
            if ($p_share) {
                $p_parent_user_id = $p_share['user_id'];
                $p_parent_share_id = $p_share['id'];
                $p_parent_level = $p_share['level'];
                if ($config["share{$p_share['level']}"]) {
                    $p_parent_amount = bcdiv(bcmul($config["share{$p_share['level']}"], $price, 4), 100, 2);
                }
                Log::log("分销数据:order_id:$order_id,user_id:$user_id,config:" . json_encode($config, 256));
                $data[] = [
                    'user_id' => $user_id,
                    'order_id' => $order_id,
                    'shop_id' => $shop_id,
                    'pay_amount' => $price,
                    'parent_user_id' => $p_parent_user_id,
                    'parent_share_id' => $p_parent_share_id,
                    'parent_level' => $p_parent_level,
                    'parent_amount' => $p_parent_amount,
                    'created_at' => $time,
                    'updated_at' => $time,
                    'order_sn' => date('YmdHis') . mt_rand(100000, 999999)
                ];
            } else {
                if ($data[0]['parent_level'] == 1) {
                    $t = bcdiv(bcmul(bcadd($config["share1"], $config["share2"], 4), $price), 100, 2);
                    $data[0]['parent_amount'] = $t;
                    Log::log("没有二级,share_id:{$share['id']},amount:{$data[0]['parent_amount']}");
                }
            }
            Log::log($data);
            if ($data) {
                $shareModel->saveAll($data);
                $order->is_share_order = 1;
                $order->save();
            }
        }

        $agentData = [];
        if ($real_store_id) {
            $order = \app\admin\model\wanlshop\Order::find($order_id);
            $agentOrderModel = new AgentOrder();
            $parent_amount = 0;
            $shop = \app\api\model\wanlshop\Shop::find($real_store_id);
            if (!empty($shop['agent_id'])) {
                $agent = \app\admin\model\wanlshop\Agent::find($shop['agent_id']);
                if ($config["agent{$agent['level']}"]) {
                    $parent_amount = bcdiv(bcmul($config["agent{$agent['level']}"], $price, 4), 100, 2);
                }
                Log::log("代理商数据:order_id:$order_id,user_id:$user_id,config:" . json_encode($config, 256));
                $agentData[] = [
                    'user_id' => $user_id,
                    'order_id' => $order_id,
                    'shop_id' => $shop_id,
                    'pay_amount' => $price,
                    'parent_agent_id' => $shop['agent_id'],
                    'parent_level' => $agent['level'],
                    'parent_amount' => $parent_amount,
                    'created_at' => $time,
                    'updated_at' => $time,
                    'order_sn' => date('YmdHis') . mt_rand(100000, 999999)
                ];
                if (!empty($agent['parent_id'])) {
                    $p_agent = \app\admin\model\wanlshop\Agent::find($agent['parent_id']);
                    if ($config["agent{$p_agent['level']}"]) {
                        $parent_amount = bcdiv(bcmul($config["agent{$p_agent['level']}"], $price, 4), 100, 2);
                    }
                    Log::log("代理商数据:order_id:$order_id,user_id:$user_id,config:" . json_encode($config, 256));
                    $agentData[] = [
                        'user_id' => $user_id,
                        'order_id' => $order_id,
                        'shop_id' => $shop_id,
                        'pay_amount' => $price,
                        'parent_agent_id' => $p_agent['id'],
                        'parent_level' => $p_agent['level'],
                        'parent_amount' => $parent_amount,
                        'created_at' => $time,
                        'updated_at' => $time,
                        'order_sn' => date('YmdHis') . mt_rand(100000, 999999)
                    ];
                } else {
                    if ($agentData[0]['parent_level'] == 1) {
                        $t = bcdiv(bcmul(bcadd($config["agent1"], $config["agent2"], 4), $price), 100, 2);
                        $agentData[0]['parent_amount'] = $t;
                        Log::log("没有二级,agent_id:{$agent['id']},amount:{$agentData[0]['parent_amount']}");
                    }
                }
            }
            Log::log($agentData);
            if ($agentData) {
                $order->is_agent_order = 1;
                $order->save();
                $agentOrderModel->saveAll($agentData);
            }
        }
        return true;
    }
}
